package com.wangjiacai.utils.ali.asr;

import com.alibaba.nls.client.protocol.asr.SpeechTranscriberResponse;
import com.alibaba.nls.client.transport.ConnectionListener;
import com.alibaba.nls.client.util.IdGen;
import com.wangjiacai.utils.ali.AliPool;
import com.wangjiacai.utils.ali.NettyConnection;
import com.wangjiacai.utils.ali.NettyNlsClient;
import com.wangjiacai.utils.ali.NettySpeechListener;

import java.util.HashMap;
import java.util.Map;


public class AliAsrPool extends AliPool {

    private SpeechTranscriber speechTranscriber;

    public AliAsrPool(NettyNlsClient nettyNlsClient, SpeechTranscriber speechTranscriber, int maxSize) {
        super(nettyNlsClient,maxSize);
        this.speechTranscriber = speechTranscriber;
    }

    @Override
    public NettyConnection getConnection(NettySpeechListener listener, ConnectionListener connectionListener) throws Exception {
        while (workSize.get()>= maxSize) {
            synchronized (waitNum) {
                waitNum.getAndIncrement();
                waitNum.wait();
                waitNum.getAndDecrement();
            }
        }
        NettyConnection nettyConnection = nettyNlsClient.connect(listener);
        nettyConnection.setAliPool(this);
        listener.setConnectionListener(connectionListener);
        return nettyConnection;
    }

    @Override
    public void free(NettyConnection nettyConnection) {
        synchronized (waitNum){
            nettyConnection.getChannel().close();
            waitNum.notify();
        }
    }

    public NettyConnection getConnection(ConnectionListener connectionListener) throws Exception {
        NettyConnection nettyConnection=getConnection(getNettySpeechListener(),connectionListener);
        synchronized (speechTranscriber){
            Map<String, Long> network = new HashMap();
            network.put("connect_cost",nettyConnection.getConnectingLatency());
            network.put("upgrade_cost", nettyConnection.getWsHandshakeLatency());
            speechTranscriber.putContext("network", network);
            speechTranscriber.setTaskId(IdGen.genId());
            nettyConnection.start(speechTranscriber);
        }
        return nettyConnection;
    }

    private NettySpeechListener getNettySpeechListener(){
        return new NettySpeechTranscriberListener(){
            @Override
            public void onClose(int closeCode, String reason) {
                super.onClose(closeCode,reason);
                this.getNettyConnection().close();
            }
            @Override
            public void onSentenceEnd(SpeechTranscriberResponse response) {
                this.getConnectionListener().onMessage(response.getTransSentenceText());
            }
        };
    }

}
